// coding: utf-8
// @Author : lryself
// @Date : 2020/10/18 21:01
// @Software: GoLand

//题目：给定一个链表，删除链表的倒数第 n 个节点，并且返回链表的头结点。
//题目url：https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
//作者题解：https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/qian-jie-dian-tan-lu-jie-dian-wan-cheng-by-xin-ru-/
package main

import (
	"fmt"
	"go_learning/src/utils"
)

func main() {
	nodeNums := 2
	e1 := removeNthFromEnd
	utils.DecoratorExample(&e1,removeNthFromEnd)
	l := ListNode{Val: 1, Next: &ListNode{Val: 2,Next: &ListNode{Val: 3,Next: &ListNode{Val: 4,Next: &ListNode{Val: 5}}}}}
	result := e1(&l, nodeNums)
	for result!=nil{
		fmt.Print(result.Val)
		result=result.Next
	}
	
}

type ListNode struct {
    Val int
    Next *ListNode
}

func removeNthFromEnd(head *ListNode, n int) *ListNode {
	lastNode:=head
	beforNode:=head
	if head.Next == nil{
		return nil
	}
	for i:=0;i<n;i++{
		lastNode=lastNode.Next
	}
	if lastNode==nil{
		return head.Next
	}
	for lastNode.Next!=nil{
		lastNode=lastNode.Next
		beforNode=beforNode.Next
	}
	beforNode.Next=beforNode.Next.Next
	return head
}